﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using Gp.Scripts.Character;
using Gp.Scripts.Database;
using Helpers;
using JetBrains.Annotations;
using QFramework;
using UnityEngine;
using Object = UnityEngine.Object;


namespace Gp.Scripts.Core
{
    public class CharacterNotFoundException : Exception
    {
        public CharacterNotFoundException() { }

        protected CharacterNotFoundException([NotNull] SerializationInfo info, StreamingContext context) : base(info,
            context) { }

        public CharacterNotFoundException(string message) : base(message) { }
        public CharacterNotFoundException(string message, Exception innerException) : base(message, innerException) { }
    }


    [AutoLoad]
    public class EntitySystem : BaseGameSystem
    {
        private Dictionary<string, BaseEntity> EntityMap;

        protected override void OnInit()
        {
            EntityMap = new Dictionary<string, BaseEntity>();
            MainArchitecture.Interface.RegisterModel(new EntityModel());
        }


        public override void OnStart()
        {
            this.RegisterEvent<Event_Entity.Spawn>(OnEntitySpawn);
            this.RegisterEvent<Event_Entity.Destroy>(OnEntityDestroy);
        }


        public void SpawnPlayerCharacter()
        {
            Global.GetSceneRoot<PlayerRoot>().LoadPlayerObject();
            var playerTrans = Global.GetSceneRoot<PlayerRoot>().PlayerCharacter.transform;
            
            var o = SceneRoot.GetSpawners()
                .OrderBy(x => x.priority)
                .FirstOrDefault();
            
            if (o != null) { playerTrans.position = o.transform.position; } 
        }


        /// <summary>
        /// 当单位初始化时，将其记录以进行快速查找
        /// </summary>
        private void OnEntitySpawn(Event_Entity.Spawn args)
        {
            LogHelper.LogInfo("单位创建", $"{args.Entity.EntityBehaviour.name} - {args.Entity.EntityBehaviour.Guid}");
            EntityMap[args.Entity.Guid] = args.Entity;
            
            // 同时创建 inventory
            // var model = this.GetModel<SceneObjectModel>();
            // if (model.IsObjectDestroyed(character.GetUniqueName())) {
            //     character.gameObject.DestroySelfGracefully();
            //     return;
            // }
            //
            // // 为其添加 Unit 组件
            // var unit = character.GetOrAddComponent<HumanoidUnit>();
            // if (character is not NpcBaseCharacter npc) return;
            // unit.prefabData = npc.Info.statData;
            // unit.PlayerNumber = PlayerConst.AIUnitNumber; 
            // unit.Initialize();
            //
            // var saveInfo = model.GetInfoData(character.GetUniqueName());
            // if (saveInfo != null) {
            //     character.transform.position = saveInfo.trans.position;
            //     character.transform.rotation = saveInfo.trans.rotation;
            //     character.gameObject.SetActive(saveInfo.isActive);
            // }
            // Global.Get<InventorySystem>().HandleCharacterBuild(character);
        }


        /// <summary>
        /// 当单位销毁时，从列表中移除记录
        /// </summary>
        private void OnEntityDestroy(Event_Entity.Destroy args)
        {
            var uid = args.Entity.Guid;
            EntityMap.Remove(uid);
        }


        public BaseCharacter FindCharacter(string characterName)
        {
            return null;
        }


        // public BaseCharacter BuildCharacter(string characterName)
        // {
        //     var item = CharacterModelsDatabase.Instance.CharacterMappingItems.FirstOrDefault(x =>
        //         x.characterName == characterName);
        //
        //     if (item == null)
        //     {
        //         throw new CharacterNotFoundException("未查找到此角色，名称：" + characterName);
        //     }
        //
        //     return BuildCharacterProcess(item);
        // }

        // public BaseCharacter BuildCharacter(int id)
        // {
        //     var item = CharacterModelsDatabase.Instance.CharacterMappingItems.FirstOrDefault(x =>
        //         x.id == id);
        //
        //     if (item == null)
        //     {
        //         throw new CharacterNotFoundException("未查找到此角色，id： " + id);
        //     }
        //
        //     return BuildCharacterProcess(item);
        // }

        // private BaseCharacter BuildCharacterProcess(CharacterMappingItem item)
        // {
        //     var obj = CharacterModelsDatabase.Instance.defaultModel;
        //     if (obj.GetCharacterAnimator() is { } animator)
        //     {
        //         animator.ChangeModel(item.model);
        //     }
        //     // 如果不为player，统一放于容器下.
        //     // obj.transform.SetParent(PlayerParent.Instance.transform);
        //
        //     obj.name = item.characterName;
        //
        //     return obj;
        // }

        // public BaseCharacter ForceGetCharacter(string characterName)
        // {
        //     BaseCharacter res = FindCharacter(characterName);
        //     return res == null ? BuildCharacter(characterName) : res;
        // }


        public CharacterMappingItem GetCharacterInfo(string name)
        {
            return CharacterModelsDatabase.Instance.CharacterMappingItems.FirstOrDefault(x => x.characterName == name);
        }

        // public IEnumerable<BaseUnit> GetCharacters()
        // {
        //     EntityMap[Unit.UnitType.Humanoid].
        // }

        public IEnumerable<BaseUnit> GetCombatants()
        {
            return this.EntityMap.Values.OfType<BaseUnit>();
        }
    }
}